﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Anke.SHManage.Model.BasicEventInfo;
using System.Net;
using System.IO;

namespace Anke.SHManage.Web.Areas.DD.Controllers
{
    public class AcceptEventController : Controller
    {
        //private static object m_SyncRoot = new Object();//互斥对象
        //
        // GET: /DD/AcceptEvent/

        //受理事件任务列表母页 根据事件编码查出基本事件信息  
        public ActionResult AcceptEventTaskList(string EventCode)
        {
           // string EventCode = "201209010725180009";
            ViewBag.EventCode = EventCode;
            //ViewBag.OrderNumber = OrderNumber;

            // 获取事件信息节点，分配tabs使用    根据事件编码查出几次受理
            Model.AcceptEventInfo info = new AcceptEventBLL().GetEventNode(EventCode);
            ViewBag.txtEC = info.EventCode;
            ViewBag.txtAO = info.AcceptOrder;
            //根据事件编码查出有出车任务的受理序号List
            List<string> LS = new AcceptEventBLL().getHadTaskOrder(EventCode);
            string neworderlist = "";
            foreach (string item in LS)
            {
                neworderlist += item + ",";
            }
            if (neworderlist.Length > 1)

                ViewBag.OrderList = neworderlist.Substring(0, neworderlist.Length - 1);

            return View();
        }


        //受理，事件，任务 页面
        public ActionResult AcceptEventTaskInfo(string EventCode, int AcceptOrder)
        {

            //string EventCode = "201004011024240017";
            //int AcceptOrder = 4;
            ViewBag.EventCode = EventCode;
            ViewBag.AcceptOrder = AcceptOrder;
            //使用事件编码和受理序号在任务表里查出有没有任务，有几次任务,任务编码是多少 传给前台页面
            int taskTimes = 0;
            taskTimes = new AcceptEventBLL().GetTaskTimes(EventCode, AcceptOrder);
            List<string> lsTaskCode = new AcceptEventBLL().GetTaskCode(EventCode, AcceptOrder);

            string newtaskCode = "";
            foreach (string item in lsTaskCode)
            {
                newtaskCode += item + ",";
            }
            if (newtaskCode.Length > 1) 

            ViewBag.taskCodes = newtaskCode.Substring(0, newtaskCode.Length - 1);

            ViewBag.taskTimes = taskTimes;

            //判断登录人修改事件信息和受理信息的权限 2016-10-27
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(1335);////判断登录人有无修改事件信息的权限
            if (Insert)
            {
                this.ViewData["RoleEventPermissionInsert"] = "Insert";//登录人有修改事件信息和受理信息的权限
            }
            return View();
        }


        #region   Info页面取内容
        //获取受理详细信息
        public ActionResult GetAcceptEventInfo()
        {
            string EventCode = Request.Form["EventCode"].ToString();
            int AcceptOrder = int.Parse(Request.Form["AcceptOrder"]);

            var list = new AcceptEventBLL().GetAcceptEventInfoByCode(EventCode, AcceptOrder);
            return Json(new { PRInfo = list }, "appliction/json", JsonRequestBehavior.AllowGet);
        }


        //获取事件详细信息
        public ActionResult GetAlarmEventInfo()
        {
            string EventCode = Request.Form["EventCode"].ToString();

            var list = new AcceptEventBLL().GetAlarmEventInfoByCode(EventCode);
            return Json(new { PLInfo = list }, "appliction/json", JsonRequestBehavior.AllowGet);
        }

        //获取事件相关电话
        public ActionResult GetAlarmCalls()
        {
            string eventCode = Request.Form["EventCode"].ToString();
            int OrderNumber = int.Parse(Request.Form["AcceptOrder"]);

            int rows = int.Parse(Request.Form["rows"]);
            int page = int.Parse(Request.Form["page"]);
            int total = 0;

            var list = new AcceptEventBLL().GetAlarmCalls(page, rows, ref total, eventCode, OrderNumber);
            if (total > 0)
            {
                return Json(new { total = total, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            else {
                return Json(new { total = 0, rows = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }



        //获取任务车辆详细信息
        public ActionResult GetTaskAmbulance()
        {

            //更改为传参数为 任务编码。  先根据事件编码和受理序号查出有几次任务，再去查TTask的任务详细内容

            string taskCode = Request.Form["taskCode"].ToString();
            //string taskCode = "2010040207031400180201";

            var list = new AcceptEventBLL().GetTaskAmbulance(taskCode);
            return Json(new { PRInfo = list }, "appliction/json", JsonRequestBehavior.AllowGet);

        }

        public ActionResult GetTaskGreenDate()
        {

           

            string taskCode = Request.Form["taskCode"].ToString();
            //string taskCode = "2010040207031400180201";

            var list = new AcceptEventBLL().GetTaskGreenDate(taskCode);
            return Json(new { GDInfo = list }, "appliction/json", JsonRequestBehavior.AllowGet);

        }

        #endregion


        //一次受理，多次任务 子页面  传参数TaskCode
        public ActionResult TaskAmbulanceDetial(string taskCode)
        {
            //string taskCode = "2010040207031400180201";
            // string taskCode = Request.Form["taskCode"].ToString();
            ViewBag.taskCode = taskCode;
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(1326);////判断登录人有无新增和修改的权限
            if (Insert)
            {
                this.ViewData["RolePermissionInsert"] = "Insert";//登录人有新增和修改的权限
            }
            return View();
        }





        //public ActionResult TelRecordList(int TelRecordCode)
        public ActionResult TelRecordList(string TelRecordCode)
        {
           // int TelRecordCode = 116;
            ViewBag.telRecordCode = TelRecordCode;
            return View();
        }

        public ActionResult GetTelRecordInfo()
        {
            //int TelRecordCode = int.Parse(Request.Form["TelRecordCode"]);
            string TelRecordCode = (Request.Form["TelRecordCode"]).ToString();
            //string taskCode = "2010040207031400180201";

            var list = new AcceptEventBLL().GetTelRecordInfo(TelRecordCode);
            return Json(new { PLInfo = list }, "appliction/json", JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改事件信息
        /// </summary>
        public ActionResult UpdateEvent(AlarmEventInfo ainfo)
        {
            P_User pUser = new P_User();
            pUser = UserOperateContext.Current.Session_UsrInfo;//获取登录人信息
            AcceptEventBLL m_BLL = new AcceptEventBLL();
            PersonInfo p = m_BLL.GetPreson(pUser.WorkCode);
            if (p != null)
                ViewData["AgentCode"] = p.Code;
            else
                ViewData["AgentCode"] = pUser.ID;

            string eEventCode = Request.Form["EventCode"];
            string eEvetnName = Request.Form["EvetnName"].ToString();
            string eArea = Request.Form["Area"].ToString();
            int eEventSourceCode = int.Parse(Request.Form["EventSourceCode"]);
            int eAccidentLevelCode = int.Parse(Request.Form["AccidentLevelCode"]);
            int eAccidentTypeCode = int.Parse(Request.Form["AccidentTypeCode"]);
            AlarmEventInfo aei = new AlarmEventInfo();
            aei.EventCode = eEventCode;
            aei.EvetnName = eEvetnName;
            aei.Area = eArea;
            aei.EventSourceCode = eEventSourceCode;
            aei.AccidentLevelCode = eAccidentLevelCode;
            aei.AccidentTypeCode = eAccidentTypeCode;


            if (new AcceptEventBLL().ModifyEvent(ainfo, ViewData["AgentCode"].ToString()) && new AcceptEventBLL().UpdateEvent(aei.EventCode, aei.EvetnName, aei.Area, aei.EventSourceCode, aei.AccidentLevelCode, aei.AccidentTypeCode))
            {
                return Json(new { IsSuccess = true, Message = "修改成功" }, "text/html", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { IsSuccess = false, Message = "修改失败" }, "text/html", JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取事件信息修改痕迹
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ActionResult GetEventCrackInfos(string EventCode)
        {
            AcceptEventBLL m_BLL = new AcceptEventBLL();
            int pageSize = 15;
            if (Request.Form["rows"] != null)
            {
                pageSize = int.Parse(Request.Form["rows"]);
            }
            //获取请求的页码
            int pageIndex = 1;
            if (Request.Form["page"] != null)
            {
                pageIndex = int.Parse(Request.Form["page"]);
            }
            int rowCount = 0;
            List<ModifyRecordInfo> list = m_BLL.GetEventCrackInfos(pageIndex, pageSize, ref rowCount, EventCode);
            return Json(new { total = rowCount, rows = list }, "text/html", JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改受理信息 2016-10-28
        /// </summary>
        public ActionResult UpdateAccept(AcceptEventInfo binfo)
        {
            P_User pUser = new P_User();
            pUser = UserOperateContext.Current.Session_UsrInfo;//获取登录人信息
            AcceptEventBLL m_BLL = new AcceptEventBLL();
            PersonInfo p = m_BLL.GetPreson(pUser.WorkCode);
            if (p != null)
                ViewData["AgentCode"] = p.Code;
            else
                ViewData["AgentCode"] = pUser.ID;

            string eEventCode = Request.Form["EventCode"];
            string eAlarmReason = Request.Form["AlarmReason"].ToString();
            string ePatientName = Request.Form["PatientName"].ToString();
            string eSex = Request.Form["Sex"].ToString();
            string eAge = Request.Form["Age"].ToString();
            string eNational = Request.Form["National"].ToString();
            string eFolk = Request.Form["Folk"].ToString();
            string eJudge = Request.Form["Judge"].ToString();
            string eLinkMan = Request.Form["LinkMan"].ToString();
            string eLinkTel = Request.Form["LinkTel"].ToString();
            string eExtension = Request.Form["Extension"].ToString();
            string eLocalAddr = Request.Form["LocalAddr"].ToString();
            string eWaitAddr = Request.Form["WaitAddr"].ToString();
            string eSendAddr = Request.Form["SendAddr"].ToString();
            bool eIsNeedLitter = Convert.ToBoolean(Request.Form["IsNeedLitter"]);       
            AcceptEventInfo ae = new AcceptEventInfo();
            ae.EventCode = eEventCode;
            ae.AlarmReason = eAlarmReason;
            ae.PatientName = ePatientName;
            ae.Sex = eSex;
            ae.Age = eAge;
            ae.National = eNational;
            ae.Folk = eFolk;
            ae.Judge = eJudge;
            ae.LinkMan = eLinkMan;
            ae.LinkTel = eLinkTel;
            ae.Extension = eExtension;
            ae.LocalAddr = eLocalAddr;
            ae.WaitAddr = eWaitAddr;
            ae.SendAddr = eSendAddr;
            ae.IsNeedLitter = eIsNeedLitter;

            if ( new AcceptEventBLL().ModifyAccept(binfo, ViewData["AgentCode"].ToString()) && new AcceptEventBLL().UpdateAccept(ae.EventCode, ae.AlarmReason, ae.PatientName, ae.Sex, ae.Age, ae.National, ae.Folk,
                ae.Judge, ae.LinkMan, ae.LinkTel, ae.Extension, ae.LocalAddr, ae.WaitAddr, ae.SendAddr, ae.IsNeedLitter))
            {
                return Json(new { IsSuccess = true, Message = "修改成功" }, "text/html", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { IsSuccess = false, Message = "修改失败" }, "text/html", JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取受理修改痕迹
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ActionResult GetAcceptCrackInfos(string EventCode)
        {
            AcceptEventBLL m_BLL = new AcceptEventBLL();
            int pageSize = 15;
            if (Request.Form["rows"] != null)
            {
                pageSize = int.Parse(Request.Form["rows"]);
            }
            //获取请求的页码
            int pageIndex = 1;
            if (Request.Form["page"] != null)
            {
                pageIndex = int.Parse(Request.Form["page"]);
            }
            int rowCount = 0;
            List<ModifyRecordInfo> list = m_BLL.GetAcceptCrackInfos(pageIndex, pageSize, ref rowCount, EventCode);
            return Json(new { total = rowCount, rows = list }, "text/html", JsonRequestBehavior.AllowGet);
        }


        #region 录音相关 add2021-07-02 plq

        /// <summary>
        /// add2021-07-02 plq 录音播放页面
        /// </summary>
        /// <param name="code"></param>
        /// <param name="buildTime"></param>
        /// <returns></returns>
        public ActionResult MediaPlayer(string code, string buildTime)
        {
            ViewBag.RecordNumber = code;
            ViewBag.BuildTime = buildTime;
            return View("MediaPlayer");
        }

        /// <summary>
        /// 获取录音文件路径，http路径
        /// add2021-07-03 plq
        /// </summary>
        /// <param name="RecordNumber"></param>
        /// <param name="CallTime"></param>
        /// <returns></returns>
        public ActionResult VideoDownLoad(string RecordNumber, string CallTime)
        {
            string strFileName = GetFileName(RecordNumber);//文件名称
            string strFilePath = GetMapPath(Convert.ToDateTime(CallTime), RecordNumber);//文件路径
            return Json(strFilePath, JsonRequestBehavior.AllowGet);
            //string strFileName = ConfigHelper.GetFileName(RecordNumber);//文件名称
            //string strFilePath = "E:/MediaPlayer/01.mp3";
            //string strFilePath = Server.MapPath(string.Format("~/{0}/{1}", "File", "01.wav"));
            //return Json(strFilePath, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取文件名称(去除后缀名)
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public static string GetFileName(string arg)
        {
            if (arg != "")
            {
                int idxa = arg.LastIndexOf(".");//点所在的位置
                int alen = arg.Length;//总长度
                return arg.Substring(0, idxa - 1);//要截取的长度
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 返回录音文件路径
        /// http路径格式 /
        /// </summary>
        /// <param name="FirstAcceptTime"></param>
        /// <param name="RecordNumber"></param>
        /// <returns></returns>
        private string GetMapPath(DateTime FirstAcceptTime, string RecordNumber)
        {
            string year = String.Format("{0:yyyy}", FirstAcceptTime);
            string month = String.Format("{0:yyyyMM}", FirstAcceptTime);
            string day = String.Format("{0:yyyyMMdd}", FirstAcceptTime);
            //string strMapPath = AppConfig.MediaClientPath + "\\" + year + "\\" + month + "\\" + day + "\\" + RecordNumber + "";
            string strMapPath = AppConfig.GetConfigString("MediaClientPath") + "/" + year + "/" + month + "/" + day + "/" + Server.UrlEncode(RecordNumber) + "";//进行URL编码
            return strMapPath;
        }

        /// <summary>
        /// 返回录音文件路径
        /// 共享文件夹路径格式 /
        /// </summary>
        /// <param name="FirstAcceptTime"></param>
        /// <param name="RecordNumber"></param>
        /// <returns></returns>
        private string GetMapPath1(DateTime FirstAcceptTime, string RecordNumber)
        {
            string year = String.Format("{0:yyyy}", FirstAcceptTime);
            string month = String.Format("{0:yyyyMM}", FirstAcceptTime);
            string day = String.Format("{0:yyyyMMdd}", FirstAcceptTime);
            string strMapPath = AppConfig.GetConfigString("MediaClientPath") + "\\" + year + "\\" + month + "\\" + day + "\\" + RecordNumber + "";
            return strMapPath;
        }

        /// <summary>
        /// Http路径录音文件下载
        /// 返回服务器上文件保存路径
        /// add2021-07-02 plq
        /// </summary>
        /// <param name="RecordNumber"></param>
        /// <param name="CallTime"></param>
        /// <returns></returns>
        public ActionResult RecordingDownload(string RecordNumber, string CallTime)
        {
            string strFileName = GetFileName(RecordNumber);//文件名称
            string strFilePath = GetMapPath(Convert.ToDateTime(CallTime), RecordNumber);//文件路径
            bool result = true;
            string str = HttpDownloadFile(strFilePath, RecordNumber, ref result);
            return Json(new { result = result, data = str }, JsonRequestBehavior.AllowGet);
        }

        ///
        /// Http下载文件：下载指定文件存储到特定目录(服务器)
        /// add2021-07-03 plq
        ///
        public static string HttpDownloadFile(string remoteUrl, string fileName, ref bool result)
        {
            result = true;
            try
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(remoteUrl) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();

                //string localPath = AppDomain.CurrentDomain.BaseDirectory + @"" + fileName;

                //格式化录音文件保存文件夹 验证是否存在
                //格式化文件夹字符串
                string folderPath = string.Format("{0}\\{1}\\Year_{2}\\Day_{3}", AppConfig.GetConfigString("MediaDownloadPath"), "AKSJRecordDownloads", System.DateTime.Now.ToString("yyyy"), System.DateTime.Now.ToString("yyyy-MM-dd"));

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                //验证文件夹 是否存在

                string localPath = folderPath + @"\" + fileName;

                //创建本地文件写入流
                Stream stream = new FileStream(localPath, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                stream.Close();
                responseStream.Close();
                return localPath;
            }
            catch (Exception ex)
            {
                result = false;
                LogUtility.Error("录音下载HttpDownloadFile:", ex.Message);
                return ex.Message;
            }
        }

        /// <summary>
        /// 录音文件下载到本地
        /// add2021-07-03 plq
        /// </summary>
        /// <param name="strFileName"></param>
        /// <param name="strFilePath"></param>
        /// <returns></returns>
        public FileStreamResult DownloadFile(string strFileName, string strFilePath)
        {
            FileStream fs = new FileStream(strFilePath, FileMode.Open);
            return File(fs, "text/plain", strFileName);
        }
        #endregion


    }
}
